#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowTitle("简单的记事本");
    // 获取到菜单栏
    QMenuBar* menuBar = this->menuBar();
    // 添加菜单
    QMenu* menu = new QMenu("文件");
    menuBar->addMenu(menu);
    // 添加菜单项
    QAction* act1 = new QAction("打开");
    QAction* act2 = new QAction("保存");
    menu->addAction(act1);
    menu->addAction(act2);
    // 指定一个输入框
    edit = new QPlainTextEdit();
    QFont font;
    font.setPixelSize(20);
    edit->setFont(font);
    this->setCentralWidget(edit);
    // 连接
    connect(act1, &QAction::triggered, this, &MainWindow::handleact1);
    connect(act2, &QAction::triggered, this, &MainWindow::handleact2);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handleact1()
{
    qDebug() << "handleact1";
    // 先弹出打开文件对话框，选择文件
    QString path = QFileDialog::getOpenFileName(this);
    // 文件名显示到状态栏
    QStatusBar* statusBar = this->statusBar();
    statusBar->showMessage(path);
    // 根据选择的路径，构造QFile对象
    QFile file(path);
    bool ret = file.open(QIODevice::ReadOnly);
    if (!ret)
    {
        // 打开失败
        statusBar->showMessage(path + "打开失败！");
        return;
    }

    // 读取文件
    QString text = file.readAll();
    // 关闭文件，不要忘记
    file.close();
    // 读到的内容设置输入框中
    edit->setPlainText(text);
}

void MainWindow::handleact2()
{
     qDebug() << "handleact2";
    // 弹出保存文件对话框
    QString path = QFileDialog::getSaveFileName(this);
    // 状态栏显示文件名
    QStatusBar* statusBar = this->statusBar();
    statusBar->showMessage(path);
    // 根据选择的路径，构造QFile对象打开
    QFile file(path);
    bool ret = file.open(QFile::WriteOnly);
    if (!ret)
    {
        statusBar->showMessage(path + "打开失败");
        return;
    }

    const QString& text = edit->toPlainText();
    file.write(text.toUtf8());
    // 关闭文件
    file.close();
}


